package com.vivo.ic.dm;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;

import com.vivo.ic.VLog;

import java.util.ArrayList;

/**
 * 网络切换帮助类
 *
 * @author wangzhenyu
 */
public class NetDealHelper {
    public static final String TAG = Constants.PRE_TAG + "NetDealHelper";

    private interface OrphanQuery {
        String[] PROJECTION = new String[]{Downloads.Column._ID, Downloads.Column.CONTROL,
                Downloads.Column.STATUS, Downloads.Column.NETWORK_CHANGED, Downloads.Column.VISIBILITY};

        int _ID = 0;
        int COLUMN_CONTROL = 1;
        int COLUMN_STATUS = 2;
        int COLUMN_NETWORK_CHANGED = 3;
        int COLUMN_VISIBILITY = 4;
    }

    /**
     * 由于网络切换暂停下载
     *
     * @param resolver
     */
    public static void netPauseDownload(ContentResolver resolver) {

        ArrayList<Long> ids = new ArrayList<Long>();
        DownloadManager manager = DownloadManager.getInstance();
        Cursor cursor = null;
        try {
            cursor = resolver.query(Downloads.Impl.CONTENT_URI, OrphanQuery.PROJECTION, null, null, null);
            if (cursor != null) {

                boolean match = false;
                for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
                    long currentId = cursor.getLong(OrphanQuery._ID);
                    int control = cursor.getInt(OrphanQuery.COLUMN_CONTROL);
                    int status = cursor.getInt(OrphanQuery.COLUMN_STATUS);
                    int changed = cursor.getInt(OrphanQuery.COLUMN_NETWORK_CHANGED);
                    int visible = cursor.getInt(OrphanQuery.COLUMN_VISIBILITY);

                    VLog.i(TAG, "netPauseDownload currentId is " + currentId + ", control is " + control
                            + ", status is " + status + ", changed is " + changed);
                    if (control == Downloads.Impl.CONTROL_RUN &&
                            (!Downloads.Impl.isStatusCompleted(status) || status == Downloads.Impl.STATUS_FILE_ERROR
                                    || status == Downloads.Impl.STATUS_HTTP_DATA_ERROR)) {
                        VLog.i(TAG, "pause download of " + currentId);
                        ContentValues values = new ContentValues();
//                        values.put(Downloads.Column.CONTROL, Downloads.Impl.CONTROL_PAUSED);
                        values.put(Downloads.Column.STATUS, Downloads.Impl.STATUS_QUEUED_FOR_WIFI);
                        values.put(Downloads.Column.NETWORK_CHANGED, Constants.CHANGE_STATE_PAUSED);
                        resolver.update(ContentUris.withAppendedId(Downloads.Impl.CONTENT_URI, currentId), values, null,
                                null);

                        // 对于不显示通知栏的下载，直接pause掉下载，不提示警告
                        if (visible != Downloads.Impl.VISIBILITY_HIDDEN
                                && visible != Downloads.Impl.VISIBILITY_VISIBLE_COMPLETED) {
                            match = true;
                        }

                        ids.add(currentId);
                    }
                }
                if (match) {
                    VLog.d(TAG, "match showNetPauseNotification()");
                    manager.getNotifier().showNetPauseNotification();
                }
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

        if (ids.size() > 0) {
            manager.notifyDownloadPausedByNetChange(Helpers.list2Array(ids));
        }
    }

    /**
     * 启动由于网络切换暂停的下载
     *
     * @param resolver
     */
    public static void startDownloadNetPaused(ContentResolver resolver) {
        ArrayList<Long> ids = new ArrayList<Long>();

        Cursor cursor = null;
        try {
            cursor = resolver.query(Downloads.Impl.CONTENT_URI, OrphanQuery.PROJECTION, null, null, null);
            if (cursor != null) {

                for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
                    long currentId = cursor.getLong(OrphanQuery._ID);
                    int control = cursor.getInt(OrphanQuery.COLUMN_CONTROL);
                    int status = cursor.getInt(OrphanQuery.COLUMN_STATUS);
                    int changed = cursor.getInt(OrphanQuery.COLUMN_NETWORK_CHANGED);

                    // 只有是因为网络切换的原因而被暂停的下载，在切到wifi时才需要继续下载

                    VLog.i(TAG, "startDownloadNetPaused currentId is " + currentId + ", control is " + control
                            + ", status is " + status + ", changed is " + changed);
                    if (!Downloads.Impl.isStatusCompleted(status) && !Downloads.Impl.isPausedManually(status, control)) {
                        VLog.i(TAG, "start net paused download of " + currentId);
                        ContentValues values = new ContentValues();
                        values.put(Downloads.Column.CONTROL, Downloads.Impl.CONTROL_RUN);
                        values.put(Downloads.Column.STATUS, Downloads.Impl.STATUS_RUNNING);
                        values.put(Downloads.Column.NETWORK_CHANGED, Constants.CHANGE_STATE_WIFI);
                        resolver.update(ContentUris.withAppendedId(Downloads.Impl.CONTENT_URI, currentId), values, null,
                                null);
                        ids.add(currentId);
                    }
                }
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        if (ids.size() > 0) {
            DownloadManager manager = DownloadManager.getInstance();
            manager.notifyDownloadStartByNetChange(Helpers.list2Array(ids));
        }
    }

    /**
     * 移动网络下启动下载
     *
     * @param resolver
     */
    public static void startDownloadInMobile(ContentResolver resolver) {
        Cursor cursor = null;
        try {
            cursor = resolver.query(Downloads.Impl.CONTENT_URI, OrphanQuery.PROJECTION, null, null, null);
            if (cursor != null) {

                for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
                    long currentId = cursor.getLong(OrphanQuery._ID);
                    int control = cursor.getInt(OrphanQuery.COLUMN_CONTROL);
                    int status = cursor.getInt(OrphanQuery.COLUMN_STATUS);
                    int changed = cursor.getInt(OrphanQuery.COLUMN_NETWORK_CHANGED);
                    VLog.i(TAG, "startDownloadInMobile currentId is " + currentId + ", control is " + control
                            + ", status is " + status + ", changed is " + changed);
                    if (!Downloads.Impl.isStatusCompleted(status)) {
                        ContentValues values = new ContentValues();
//                        values.put(Downloads.Column.CONTROL, Downloads.Impl.CONTROL_RUN);
                        values.put(Downloads.Column.STATUS, Downloads.Impl.STATUS_RUNNING);
                        values.put(Downloads.Column.NETWORK_CHANGED, Constants.CHANGE_STATE_MOBILE);
                        resolver.update(ContentUris.withAppendedId(Downloads.Impl.CONTENT_URI, currentId), values, null,
                                null);
                    }
                }
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

    public static void pauseDownloadByNetChange(ContentResolver resolver) {
        Cursor cursor = null;
        try {
            cursor = resolver.query(Downloads.Impl.CONTENT_URI, OrphanQuery.PROJECTION, null, null, null);
            if (cursor != null) {

                for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
                    long currentId = cursor.getLong(OrphanQuery._ID);
                    int control = cursor.getInt(OrphanQuery.COLUMN_CONTROL);
                    int status = cursor.getInt(OrphanQuery.COLUMN_STATUS);
                    int changed = cursor.getInt(OrphanQuery.COLUMN_NETWORK_CHANGED);

                    VLog.i(TAG, "pauseDownloadByNetChange() currentId is " + currentId + ", control is " + control
                            + ", status is " + status + ", changed is " + changed);
                    if (!Downloads.Impl.isStatusCompleted(status)) {
                        ContentValues values = new ContentValues();
                        values.put(Downloads.Column.CONTROL, Downloads.Impl.CONTROL_RUN);
                        values.put(Downloads.Column.STATUS, Downloads.Impl.STATUS_PAUSED_BY_APP);
                        values.put(Downloads.Column.NETWORK_CHANGED, Constants.CHANGE_STATE_PAUSED);
                        resolver.update(ContentUris.withAppendedId(Downloads.Impl.CONTENT_URI, currentId), values, null,
                                null);

                    }
                }
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }
}
